import store from '@/store/index.js'
let socketTask = null;

export const connectSocket = (wssurl) => {
	if (!socketTask) {
		socketTask = uni.connectSocket({
			url: wssurl,
			complete: () => {
				console.log('WebSocket连接尝试');
			}
		});

		socketTask.onOpen(() => {
			console.log('WebSocket连接已打开！');
		});

		socketTask.onClose(() => {
			uni.reLaunch({
				url: '/pages/home/index'
			});
			console.log('WebSocket连接关闭，请检查！');
		});

		socketTask.onError((res) => {
			uni.reLaunch({
				url: '/pages/home/index'
			});
			console.log('WebSocket连接失败，请检查！', res);
		});
	}
};

export const getSocketMessage = (callback) => {
	if (socketTask) {
		socketTask.onMessage((res) => {
			if (callback) {
				try {
					const event = JSON.parse(res.data);
					callback(event);
				} catch (e) {
					console.error('解析消息失败:', e);
				}
			}
		});
	} else {
		console.warn('WebSocket未初始化');
	}
};

export const sendSocketMessage = (msg) => {
	if (socketTask) {
		socketTask.send({
					data: JSON.stringify(msg),
					success: () => console.log('消息发送成功'),
					fail: (err) => console.error('消息发送失败:', err)
				});
	} else {
		console.warn('WebSocket未初始化');
	}
};

export const closeSocketAI = () => {
	if (socketTask) {
		socketTask.close({
			success: () => {
				socketTask = null;
				console.log('WebSocket连接已关闭');
			},
			fail: (err) => console.error('关闭WebSocket失败:', err)
		});
	} else {
		console.warn('WebSocket未连接');
	}
};